import CodeMirrorWrapper from '@/components/CodeMirrorWrapper';
import ToolPageTemplate from '@/components/ToolPageTemplate';
import { useTextCompare } from '@/hooks/tools/useTextCompare';
import AutoFixHighIcon from '@mui/icons-material/AutoFixHigh';
import ClearIcon from '@mui/icons-material/Clear';
import CompareArrowsIcon from '@mui/icons-material/CompareArrows';
import ContentCopyIcon from '@mui/icons-material/ContentCopy';
import DifferenceIcon from '@mui/icons-material/Difference';
import {
  Alert,
  Box,
  Button,
  Chip,
  Divider,
  FormControl,
  FormControlLabel,
  Grid,
  Paper,
  Radio,
  RadioGroup,
  Snackbar,
  Stack,
  Typography,
  alpha
} from '@mui/material';
import { useState } from 'react';

const TextComparePage = () => {
  const [snackbarOpen, setSnackbarOpen] = useState(false);
  const [snackbarMessage, setSnackbarMessage] = useState('');

  const {
    text1,
    text2,
    setText1,
    setText2,
    compareResult,
    error,
    compareMode,
    setCompareMode,
    compareTexts,
    copyAsText,
    copyAsHTML,
    loadExample,
    clearTexts
  } = useTextCompare();

  const handleCopy = (format: 'text' | 'html') => {
    let success = false;
    let formatName = '';

    switch (format) {
      case 'text':
        success = copyAsText();
        formatName = '文本';
        break;
      case 'html':
        success = copyAsHTML();
        formatName = 'HTML';
        break;
    }

    if (success) {
      setSnackbarMessage(`已复制为${formatName}格式`);
      setSnackbarOpen(true);
    }
  };

  const handleCloseSnackbar = () => {
    setSnackbarOpen(false);
  };

  const handleCompareMode = (event: React.ChangeEvent<HTMLInputElement>) => {
    setCompareMode(event.target.value as 'line' | 'character');
  };

  return (
    <ToolPageTemplate
      title="文本对比工具"
      description="比较两段文本的差异，支持逐行或逐字符对比"
      category="文本处理"
      categoryColor="#FFA940"
    >
      {/* 快速信息区域 */}
      <Box sx={{ mb: 4 }}>
        <Stack direction="row" spacing={2} justifyContent="center" flexWrap="wrap">
          <Chip
            icon={<DifferenceIcon />}
            label="文本对比"
            variant="outlined"
            color="primary"
          />
          <Chip
            icon={<CompareArrowsIcon />}
            label="多模式对比"
            variant="outlined"
            color="secondary"
          />
        </Stack>
      </Box>

      {/* 对比设置 */}
      <Paper
        elevation={0}
        sx={{
          p: 3,
          mb: 4,
          borderRadius: 3,
          border: '1px solid',
          borderColor: 'divider'
        }}
      >
        <Typography
          variant="h6"
          sx={{
            mb: 3,
            fontWeight: 700,
            display: 'flex',
            alignItems: 'center',
            gap: 1
          }}
        >
          <DifferenceIcon color="primary" />
          对比设置
        </Typography>

        <Grid container spacing={3} alignItems="center">
          <Grid item xs={12} sm={6}>
            <FormControl component="fieldset">
              <Typography variant="subtitle2" gutterBottom sx={{ fontWeight: 600 }}>
                对比模式:
              </Typography>
              <RadioGroup
                row
                name="compareMode"
                value={compareMode}
                onChange={handleCompareMode}
              >
                <FormControlLabel value="line" control={<Radio />} label="逐行对比" />
                <FormControlLabel value="character" control={<Radio />} label="逐字符对比" />
              </RadioGroup>
            </FormControl>
          </Grid>
          <Grid item xs={12} sm={6}>
            <Stack direction="row" spacing={2}>
              <Button
                variant="outlined"
                color="error"
                onClick={clearTexts}
                startIcon={<ClearIcon />}
                sx={{
                  borderRadius: '20px',
                  textTransform: 'none',
                  fontWeight: 600
                }}
              >
                清空文本
              </Button>
            </Stack>
          </Grid>
        </Grid>
      </Paper>

      <Stack spacing={4}>
        {/* 编辑器部分 */}
        <Paper
          elevation={0}
          sx={{
            p: 3,
            borderRadius: 3,
            border: '1px solid',
            borderColor: 'divider',
            width: '100%'
          }}
        >
          <Box sx={{
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            mb: 3
          }}>
            <Typography
              variant="h6"
              sx={{
                fontWeight: 700,
                display: 'flex',
                alignItems: 'center',
                gap: 1
              }}
            >
              <DifferenceIcon color="primary" />
              文本编辑器
            </Typography>
            <Button
              variant="text"
              size="small"
              startIcon={<AutoFixHighIcon />}
              onClick={loadExample}
              sx={{
                textTransform: 'none',
                fontWeight: 600,
                color: 'primary.main',
                '&:hover': {
                  bgcolor: 'primary.main',
                  color: 'primary.contrastText'
                }
              }}
            >
              加载示例
            </Button>
          </Box>

          <Grid container spacing={3}>
            <Grid item xs={12} md={6}>
              <Typography variant="subtitle2" gutterBottom sx={{ fontWeight: 600 }}>
                原始文本:
              </Typography>
              <Box sx={{ borderRadius: 2, overflow: 'hidden', border: '1px solid', borderColor: 'divider' }}>
                <CodeMirrorWrapper
                  label=""
                  value={text1}
                  onChange={setText1}
                  height="300px"
                  language="text"
                  placeholder="请输入原始文本..."
                />
              </Box>
            </Grid>

            <Grid item xs={12} md={6}>
              <Typography variant="subtitle2" gutterBottom sx={{ fontWeight: 600 }}>
                比较文本:
              </Typography>
              <Box sx={{ borderRadius: 2, overflow: 'hidden', border: '1px solid', borderColor: 'divider' }}>
                <CodeMirrorWrapper
                  label=""
                  value={text2}
                  onChange={setText2}
                  height="300px"
                  language="text"
                  placeholder="请输入要比较的文本..."
                />
              </Box>
            </Grid>
          </Grid>

          <Box sx={{ textAlign: 'center', mt: 3 }}>
            <Button
              variant="contained"
              size="large"
              onClick={compareTexts}
              startIcon={<CompareArrowsIcon />}
              sx={{
                borderRadius: '25px',
                px: 4,
                py: 1.5,
                textTransform: 'none',
                fontWeight: 600,
                fontSize: '1.1rem'
              }}
            >
              开始对比
            </Button>
          </Box>
        </Paper>

        {/* 对比结果 */}
        {compareResult && (
          <Paper
            elevation={0}
            sx={{
              p: 3,
              borderRadius: 3,
              border: '1px solid',
              borderColor: 'divider',
              width: '100%'
            }}
          >
            <Typography
              variant="h6"
              sx={{
                mb: 3,
                fontWeight: 700,
                display: 'flex',
                alignItems: 'center',
                gap: 1
              }}
            >
              🎯 对比结果
            </Typography>

            {/* 统计信息 */}
            <Box sx={{ mb: 3 }}>
              <Grid container spacing={2}>
                <Grid item xs={4}>
                  <Box sx={{
                    p: 2,
                    bgcolor: alpha('#4caf50', 0.1),
                    borderRadius: 2,
                    textAlign: 'center',
                    border: `1px solid ${alpha('#4caf50', 0.3)}`
                  }}>
                    <Typography variant="h6" color="#4caf50" sx={{ fontWeight: 700 }}>
                      {compareResult.totalAdded}
                    </Typography>
                    <Typography variant="body2" color="text.secondary">
                      新增
                    </Typography>
                  </Box>
                </Grid>
                <Grid item xs={4}>
                  <Box sx={{
                    p: 2,
                    bgcolor: alpha('#f44336', 0.1),
                    borderRadius: 2,
                    textAlign: 'center',
                    border: `1px solid ${alpha('#f44336', 0.3)}`
                  }}>
                    <Typography variant="h6" color="#f44336" sx={{ fontWeight: 700 }}>
                      {compareResult.totalRemoved}
                    </Typography>
                    <Typography variant="body2" color="text.secondary">
                      删除
                    </Typography>
                  </Box>
                </Grid>
                <Grid item xs={4}>
                  <Box sx={{
                    p: 2,
                    bgcolor: alpha('#9e9e9e', 0.1),
                    borderRadius: 2,
                    textAlign: 'center',
                    border: `1px solid ${alpha('#9e9e9e', 0.3)}`
                  }}>
                    <Typography variant="h6" color="#9e9e9e" sx={{ fontWeight: 700 }}>
                      {compareResult.totalEqual}
                    </Typography>
                    <Typography variant="body2" color="text.secondary">
                      相同
                    </Typography>
                  </Box>
                </Grid>
              </Grid>
            </Box>

            {/* 差异详情 */}
            <Box sx={{
              maxHeight: '400px',
              overflow: 'auto',
              border: '1px solid',
              borderColor: 'divider',
              borderRadius: 2,
              p: 2,
              bgcolor: 'background.paper'
            }}>
              {compareResult.lineDiffs.map((line, lineIndex) => (
                <Box key={lineIndex} sx={{
                  fontFamily: 'monospace',
                  whiteSpace: 'pre-wrap',
                  mb: 0.5,
                  minHeight: '1.2em',
                  fontSize: '0.875rem'
                }}>
                  {line.map((diff, diffIndex) => (
                    <span
                      key={diffIndex}
                      style={{
                        backgroundColor: diff.type === 'add'
                          ? 'rgba(76, 175, 80, 0.15)'
                          : diff.type === 'remove'
                            ? 'rgba(244, 67, 54, 0.15)'
                            : 'transparent',
                        color: diff.type === 'add'
                          ? '#2e7d32'
                          : diff.type === 'remove'
                            ? '#d32f2f'
                            : 'inherit',
                        textDecoration: diff.type === 'add'
                          ? 'underline'
                          : diff.type === 'remove'
                            ? 'line-through'
                            : 'none',
                        padding: '1px 2px',
                        borderRadius: '2px'
                      }}
                    >
                      {diff.value}
                    </span>
                  ))}
                </Box>
              ))}
            </Box>

            <Divider sx={{ my: 3 }} />

            {/* 复制按钮 */}
            <Typography variant="subtitle2" gutterBottom sx={{ fontWeight: 600 }}>
              复制结果:
            </Typography>
            <Stack direction="row" spacing={2} justifyContent="center">
              <Button
                variant="outlined"
                startIcon={<ContentCopyIcon />}
                onClick={() => handleCopy('text')}
                sx={{
                  borderRadius: '20px',
                  textTransform: 'none',
                  fontWeight: 600
                }}
              >
                复制为文本
              </Button>
              <Button
                variant="outlined"
                startIcon={<ContentCopyIcon />}
                onClick={() => handleCopy('html')}
                sx={{
                  borderRadius: '20px',
                  textTransform: 'none',
                  fontWeight: 600
                }}
              >
                复制为HTML
              </Button>
            </Stack>
          </Paper>
        )}
      </Stack>

      {/* 错误提示 */}
      <Snackbar
        open={!!error}
        autoHideDuration={6000}
        anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
      >
        <Alert severity="error" sx={{ width: '100%' }}>
          {error}
        </Alert>
      </Snackbar>

      {/* 成功提示 */}
      <Snackbar
        anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
        open={snackbarOpen}
        autoHideDuration={3000}
        onClose={handleCloseSnackbar}
      >
        <Alert severity="success" sx={{ width: '100%' }}>
          {snackbarMessage}
        </Alert>
      </Snackbar>
    </ToolPageTemplate>
  );
};

export default TextComparePage; 